/* eslint-disable */
import { createStore } from 'vuex'
import LC from 'leancloud-storage/live-query'
import superagent from 'superagent'

// callback


LC.init({
  appId: "GuYDa29KjnPM9odsUsIUq5Ez-gzGzoHsz",
  appKey: "nNzmWVKoTHkJGKtIsx0Gc0OV",
  serverURL: "https://dbmy.water-crystal.org"
});

const tests = ['space', 'append', 'update', 'snapshot', 'aggmax', 'aggdur', 'etpc', 'reachable', 'ehistory', 'oltp', 'olap', '', '', '', '', '', '']

function arr2map(lst){
    let rrr = {}
    for(let index in lst){
        rrr[lst[index]] = index
    }
    return rrr
}
// 创建一个新的 store 实例
const store = createStore({
    state () {
        return {
            results: [
                {
                    test: 'space',
                    dataset: 'syn',
                    db: 'pg',
                    value: 90
                },
            ],
            jenkins_test:[
                
            ],
            benchmarks: [

            ],
            jenkins_jobs:{},
            sortbyname: true,
        }
    },
    getters:{
        unionTests(state){
            let jidMap = {}
            const union_results = []
            for(let t of state.results){
                let key = t.test+t.content.jenkinsId
                jidMap[key] = t
                union_results.push(t)
            }
            for(let t of state.jenkins_test){
                let key = t.test+t.jenkinsId
                if(key in jidMap){
                    let tt = jidMap[key]
                    tt.jenkins = t
                }else{
                    union_results.push({
                        test: t.test,
                        dataset: t.dataset,
                        db: t.db,
                        createdAt: t.createdAt,
                        content: t,
                        jenkins: t,
                    })
                }
            }
            return union_results
        },
        grpByJenkinsId(state){
            let jidMap = {}
            for(let t of state.results){
                let jid = t.content.jenkins?t.content.jenkins:-1
                let key = t.test+jid
                if(!(key in jidMap)) jidMap[key] = []
                jidMap[key].push(t)
            }
            for(let t of state.jenkins_test){
                let key = t.test+t.jenkinsId
                if(!(key in jidMap)) jidMap[key] = []
                jidMap[key].push({
                    test: t.test,
                    dataset: t.dataset,
                    db: t.db,
                    createdAt: t.createdAt,
                    content: t,
                    jenkins: t,
                })
            }
            return jidMap
        },
        grpResDataDbSize(state, getters){
            const tests = getters.unionTests
            let res = {}
            for(let t of tests){
                if(t.test && t.dataset && t.db && t.content.msize && t.content.device == 'data' && t.content.duration){
                    let key = (t.dataset+':'+t.db+t.content.msize.slice(1)).toLowerCase()
                    if(!(key in res)) res[key]=[]
                    res[key].push(t)
                }
            }
            return res
        },
        dbList(state, getters){
            const res = getters.grpResDataDbSize
            let uniq = {}
            for(let key in res){
                let arr = key.split(':')
                let dbName = arr[1]
                let t = res[key][0].createdAt.getTime()
                if(dbName in uniq){
                    if(t<uniq[dbName]) t=uniq[dbName]
                }
                uniq[dbName] = t
            }
            let result = []
            for(let key in uniq){
                result.push([key,uniq[key]])
            }
            // let orderSize = arr2map(['01', '1', '5', '9', 'all', '0'])
            // let orderDb = arr2map(['tgk', 'pg', 'ma', 'n1', 'n2'])
            // if(state.sortbyname){
            //     result.sort((a,b)=>{
            //         let aArr = a.split('.')
            //         let bArr = b.split('.')
            //         let r = orderDb[aArr[0]]-orderDb[bArr[0]]
            //         if(r==0) return orderSize[aArr[1]]-orderSize[bArr[1]];
            //         else return r
            //     })
            // }else{
            //     result.sort((a,b)=>{
            //         let aArr = a.split('.')
            //         let bArr = b.split('.')
            //         let r = orderSize[aArr[1]]-orderSize[bArr[1]]
            //         if(r==0) return orderDb[aArr[0]]-orderDb[bArr[0]]
            //         else return r
            //     })
            // }
            result.sort((a,b)=>{
                return b[1] - a[1]
            })
            return result.map(i=> i[0])
        }
    },
    
    mutations: {
        clearAllResult(state){
            state.results = []
        },
        addSpace(state, spaceResults) {
            spaceResults.map(c=>{
                return {
                    test: 'space',
                    dataset: c.dataset,
                    db: c.db,
                    createdAt: c.createdAt,
                    content: c
                }
            }).forEach(item => {
                state.results.push(item)
            });
        },
        addTest(state, testResults) {
            testResults.map(c=>{
                return {
                    test: c.test,
                    dataset: c.dataset,
                    db: c.db,
                    createdAt: c.createdAt,
                    content: c
                }
            }).forEach(item => {
                state.results.push(item)
            });
        },
        addJenkinsTest(state, tests){
            for(let t of tests){
                state.jenkins_test.push(t)
            }
        },
        addJenkinsJobMeta(state, job){
            let pp = {}
            for(let p of job[1]){
                pp[p.name] = p.defaultParameterValue.value
            }
            let meta = state.jenkins_jobs
            meta[job[0]] = pp
            state.jenkins_jobs = meta
        },
        addBenchmark(state, benchmarks){
            state.benchmarks = benchmarks
        }
    },
    actions:{
        async initialAll({commit}){
            commit('clearAllResult')
            this.dispatch('initSpace')
            this.dispatch('initTest')
            this.dispatch('initJenkins')
            // this.dispatch('initBenchmark')
        },
        async initSpace({commit}){
            const query = new LC.Query('TestMilestone');
            // query.limit(3)
            query.equalTo('extra', 'build')
            query.descending('createdAt');
            const spaceTests = await query.find()
            commit('addSpace', spaceTests.map(c=> {
                return {
                    id: c.id,
                    dataset: c.get('Dataset'),
                    db: c.get('DB'),
                    msize: c.get('MSize'),
                    dbtype: c.get('db_type'),
                    detail: c.get('detail'),
                    device: c.get('device'),
                    duration: c.get('duration'),
                    jenkins: c.get('jenkinsId'),
                    extra: c.get('extra'),
                    trange: c.get('tp_range'),
                    createdAt: c.createdAt
                }
            }))
        },
        async initTest({commit}){
            const query = new LC.Query('TGraphTest');
            // query.limit(3)
            query.descending('createdAt');
            const tests = await query.find()
            commit('addTest', tests.map(c=> {
                const milestone = c.get('DB')
                const arr = milestone.split('_')
                const testFullName = c.get('TestName')
                const tmp0 = testFullName.split('@')
                const tmp1 = tmp0[0].split('_')
                const tmp2 = tmp0[1].split('^')
                return {
                    id: c.id,
                    dataset: c.get('Dataset'),
                    db: arr[2],
                    msize: 't'+c.get('MSize'),
                    test: tmp1[3],
                    fullname: testFullName,
                    device: c.get('device'),
                    duration: c.get('duration'),
                    jenkinsId: c.get('jenkinsId'),
                    maxcon: c.get('maxCon'),
                    reqcnt: tmp1[4],
                    begintime: tmp2[1],
                    createdAt: c.createdAt
                }
            }))
        },
        async initJenkins({commit}){
            superagent
            .get('http://114.116.102.73:5000/jenkins_jobs')
            // .get('http://localhost:5000/jenkins_jobs')
            .end((err, res) => {
                console.log(res.body.content)
                const jobs = res.body.content
                let build = jobs['build']
                commit('addJenkinsJobMeta', ['build', build.params])
                let builds = build.recent_builds
                commit('addJenkinsTest', builds.map(b=> {
                    return {
                        'dataset': b.dataset,
                        'test': 'space',
                        'db': b.db_name.toLowerCase(),
                        'createdAt': new Date(b.createdAt*1000),
                        'msize': b.data_size.toLowerCase(),
                        'duration': b.duration /1000,
                        'running': b.building,
                        status: b.result.toLowerCase(),
                        device: b.device,
                        jenkinsId: b.jid,
                    }
                }))
                let test = jobs['test']
                commit('addJenkinsJobMeta', ['test', test.params])
                let tests = test.recent_builds
                commit('addJenkinsTest', tests.map(t=> {
                    let arr = t.milestone.split('_')
                    let dataset = arr[1]
                    let db = arr[2]
                    let msize = 't.'+arr[3]
                    arr = t.benchmark_name.split('_')
                    let reqcnt = parseInt(arr[4])
                    let duration = t.duration / 1000
                    let test = arr[3]
                    return {
                        dataset, test, reqcnt, db, msize, duration,
                        device: t.db_host,
                        createdAt: new Date(t.createdAt*1000),
                        maxcon: parseInt(t.max_connection),
                        running: t.building,
                        status: t.result.toLowerCase(),
                        jenkinsId: t.jid,
                    }
                }))
            });
        },
        
        async buildJenkins({commit}, name, args){
            superagent
            .post('http://114.116.102.73:5000/build_job/'+name)
            .send(args)
            // .get('http://15501121652.qicp.vip:40147/benchmark')
            .end((err, res) => {
                console.log(res.body)
            });
            this.dispatch('initJenkins')
        },
        async initBenchmark({commit}){
            superagent
            .get('http://114.116.102.73:5000/benchmark')
            // .get('http://15501121652.qicp.vip:40147/benchmark')
            .end((err, res) => {
                console.log(res.body.content)
                const blst = res.body.content
                var earliestTime = 4200000000
                const formatted = blst.map(v=>{
                    const arr = v[0].split('_')
                    const t = new Date(v[1])
                    if(t.getMilliseconds()/1000>earliestTime) earliestTime = t.getMilliseconds()/1000
                    return {
                        dataset: arr[1],
                        test: arr[3],
                        msize: arr[2].slice(2),
                        rqcnt: arr[4],
                        fsize: v[2],
                        createdAt: t
                    }
                })
                commit('addBenchmark', formatted)
            });
        },
    }
})

export default store